package Servlet;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import User.User;
import User.UserManager;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	private static String[] getParams(HttpServletRequest req, String[] fields){
		String[] ret = new String[fields.length];
		for (int i = 0; i < ret.length; ++i)
			ret[i] = req.getParameter(fields[i]);
		return ret;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			String method = request.getParameter("method");
	        if (method == null) {
	            return;
	        }
	        else if (method.equalsIgnoreCase("register")) {
	            register(request, response);
	        }
	        else if (method.equalsIgnoreCase("update")) {
	            update(request, response);
	        }
	        else if (method.equalsIgnoreCase("login")) {
	            login(request, response);
	        }
		}
		catch(Exception exp){
			HttpSession session = request.getSession();
			session.setAttribute("alert", exp.getMessage());
			request.getRequestDispatcher("/alert.jsp").forward(request, response);
		}
	}
	
	protected void register(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setCharacterEncoding("UTF-8");
		// PrintWriter pw = response.getWriter();
		String[] fieldNames = {
			"userID", "userName", "password", "dept", "phone",
			"email", "type"
		};
		String[] params = new String[fieldNames.length];
		for (int i = 0; i < fieldNames.length; ++i){
			params[i] = request.getParameter(fieldNames[i]);
			if (params[i] == null) params[i] = "";
		}
		
		User user = new User();
		user.setID(Integer.parseInt(params[0]));
		user.setName(params[1]);
		user.setPassword(params[2]);
		user.setDept(params[3]);
		user.setPhone(params[4]);
		user.setEmail(params[5]);
		user.setType(User.getType(params[6]));
		String[] courseIDs = request.getParameterValues("course");
		if (courseIDs != null)
			for (String id : courseIDs)
				user.addCourse(Integer.parseInt(id));
		UserManager.registerUser(user);
		
		request.getSession().setAttribute("user", user);
		Alert.setAlertMsg(request, "注册成功", "index.jsp", "green");
		response.sendRedirect("alert.jsp");
	}
	
	protected void update(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
	}
	
	protected void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String[] fields = {"type", "userID", "password"};
		String[] values = getParams(request, fields);
		for (int i = 0; i < fields.length; ++i)
			if (values[i] == null)
				throw new Exception("参数为空：" + fields[i]);
		
		User user = UserManager.getUser(
				Integer.parseInt(values[0]), 
				Integer.parseInt(values[1]),
				values[2]);
		
		if (user == null) throw new Exception("登陆失败");
		request.getSession().setAttribute("user", user);
		
		String link;
		switch (user.getType()){
		case User.STUDENT:
			link = "student.jsp";
			break;
		case User.TEACHER:
			link = "teacher.jsp";
			break;
		default:
			link = "index.jsp";
		}
		response.sendRedirect(link);
	}
}










